package cn.client.utlis

import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.util.Log
import android.webkit.MimeTypeMap
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.math.roundToInt

fun uriToFileApiQ(uri: Uri?, context: Context): File? {
    if (uri == null) {
        Log.d("uriToFileApiQ","返回null")
        return null
    }

    // 检查Uri方案是否为文件方案
    if (uri.scheme == ContentResolver.SCHEME_FILE) {
        Log.d("uriToFileApiQ","返回uri.path")
        return uri.path?.let { File(it) }
    }

    // 检查Uri方案是否为内容方案
    if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
        val contentResolver = context.contentResolver
        val displayName =
            "${System.currentTimeMillis()}${((Math.random() + 1) * 1000).roundToInt()}." +
                    MimeTypeMap.getSingleton()
                        .getExtensionFromMimeType(contentResolver.getType(uri))

        try {
            val inputStream = contentResolver.openInputStream(uri)
            val cacheDir = context.cacheDir.absolutePath
            val cacheFile = File(cacheDir, displayName)
            val outputStream = FileOutputStream(cacheFile)

            // 使用Kotlin标准库复制流
            inputStream.use { it?.copyTo(outputStream) }
            Log.d("uriToFileApiQ","返回cacheFile")
            return cacheFile
        } catch (e: IOException) {
            Log.d("uriToFileApiQ","异常信息：$e")
            e.printStackTrace()
        }
    }
    Log.d("uriToFileApiQ","返回null")
    return null
}